package leetcode.array;

/**
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * <p>
 * 请必须使用时间复杂度为 O(log n) 的算法。
 */
public class SearchInsertDemo {

    public static void main(String[] args) {
//        int[] nums = new int[]{1, 3, 5, 6, 7, 9, 12, 24, 25, 27, 39, 30, 33, 35, 37};
//        int target = 33;
        int[] nums = new int[]{1,3};
        int target = 0;
//        System.out.println(searchInsert(nums, target));
        System.out.println(binarySearchByWhile(nums, target));
    }

    /**
     * while循环实现二分查找
     *
     * @param nums
     * @param target
     * @return
     */
    private static int binarySearchByWhile(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                return middle;
            }
            if (nums[middle] < target) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }
        return left;
    }

    public static int searchInsert(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        if (nums.length == 1 && nums[0] >= target) {
            return 0;
        }
        if (nums.length == 1 && nums[0] < target) {
            return 1;
        }
        int left = 0, right = nums.length - 1;
        return search(nums, target, left, right);
    }

    private static int search(int[] nums, int target, int left, int right) {
        if (left > right) {
            return left;
        }
        int middle = (left + right) / 2;
        if (nums[middle] == target) {
            return middle;
        }
        if (nums[middle] < target) {
            middle = search(nums, target, middle + 1, right);
        } else {
            middle = search(nums, target, left, middle - 1);
        }
        return middle;
    }

    /**
     * 递归方式二分查找
     * 也可以while循环方式
     *
     * @param nums   原始数据
     * @param target 目标值
     * @param left   左下标
     * @param right  右下标
     * @return 索引
     */
    private static int binarySearch(int[] nums, int target, int left, int right) {
        int middle = (left + right) / 2;
        if (nums[middle] == target) {
            return middle;
        }
        if (left == right) {
            return -1;
        }
        if (nums[middle] < target) {
            middle = search(nums, target, middle + 1, right);
        } else {
            middle = search(nums, target, left, middle - 1);
        }
        return middle;
    }
}
